package org.example.classtopia.Utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Component
@Service
@Slf4j
public class TokenUtils {
    @Value("${token.privateKey}")
    private String privateKey;

    //加密Token
    public String getToken(String userId, String userRole){
        String Token = JWT
                .create()
                .withClaim("userId", userId)
                .withClaim("userRole", userRole)
                .withClaim("timeStamp", System.currentTimeMillis())
                .sign(Algorithm.HMAC256(privateKey));
        return Token;
    }

    //解密Token
    public Map<String, String> parseToken(String token){
        HashMap<String, String> map = new HashMap<>();
        DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(privateKey)).build().verify(token);
        Claim userId = decodedJWT.getClaims().get("userId");
        Claim userRole = decodedJWT.getClaim("userRole");
        Claim timeStamp = decodedJWT.getClaim("timeStamp");
        map.put("userId", userId.asString());
        map.put("userRole", userRole.asString());
        map.put("timeStamp", timeStamp.asLong().toString());

        return map;
    }
}
